<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item label="输液方式" prop="infusionType">
          <el-select v-model="queryParams.infusionType" class="width-120" clearable placeholder="请选择输液方式">
            <el-option
              v-for="dict in dictDataMap['infusion_type_dict']"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="途径" prop="channel">
          <el-input
            v-model="queryParams.channel"
            clearable
            placeholder="请输入途径"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['business:infusionType:add']"
          plain
          type="primary"
          @click="handleAdd"
        >
          <template
            #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['business:infusionType:remove']"
          :disabled="multiple"
          plain
          type="danger"
          @click="handleDelete"
        >
          <template #icon>
            <i-ep-delete/>
          </template>
          删除
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive :border="true" :data="infusionTypeList" :header-cell-style="$headerCellStyle"
              :stripe="true" highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" type="selection" width="55"/>
      <el-table-column :align="'center'" label="输液方式名称" prop="infusionTypeName"/>
      <el-table-column :align="'center'" label="途径名称" prop="channelName"/>
      <el-table-column :align="'center'" label="备注信息" prop="remarks"/>
      <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="220">
        <template #default="scope">
          <el-button
            v-hasPerm="['business:infusionType:edit']"
            type="success"
            @click="handleUpdate(scope.row)"
          >
            <template #icon>
              <i-ep-edit/>
            </template>
            修改
          </el-button>
          <el-button
            v-hasPerm="['business:infusionType:remove']"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改输液方式配置对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="输液方式">
          <el-radio-group v-model="form.infusionType" @change="infusionTypeChange">
            <el-radio
              v-for="dict in dictDataMap['infusion_type_dict']"
              :key="dict.dictValue"
              :value="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="途径" prop="channel">
          <administration-index :clearable="false" :placeholder="'请选择途径'" :value="form.channel" style="width: 100%"
                                @administrationInfoChange="administrationInfoChange($event)"/>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" :rows="3" placeholder="请输入备注信息"
                    type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: "InfusionType"
}
</script>

<script lang="ts" setup>
import {
  addInfusionType,
  delInfusionType,
  getInfusionType,
  selectPageInfusionType,
  updateInfusionType
} from "@/api/infusion/infusionType";

import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user.ts";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('infusion_type_dict'))

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const {proxy} = getCurrentInstance() as any;

const formRef = ref();
const queryParamsRef = ref()
const infusionTypeList = ref([]);
const open = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  infusionType: "",
  channel: "",
  orgId: userInfo.orgId,
  remarks: "",
  infusionTypeName: "",
  channelName: "",
  createByName: "",
  updateByName: "",
  orgName: ""
})

const form = ref<any>({
  infusionType: "1",
  channel: "",
  orgId: queryParams.value.orgId,
  remarks: "",
  infusionTypeName: "",
  channelName: "",
  createByName: "",
  updateByName: "",
  orgName: ""
})

const rules = ref({
  infusionType: [
    {required: true, message: "输液方式不能为空", trigger: "change"}
  ],
  channel: [
    {required: true, message: "途径不能为空", trigger: "change"}
  ]
})


/** 查询输液方式配置列表 */
function getList() {
  selectPageInfusionType(queryParams.value).then((response: any) => {
    infusionTypeList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    infusionType: "1",
    channel: "",
    orgId: queryParams.value.orgId,
    createBy: "",
    createTime: "",
    updateBy: "",
    updateTime: "",
    remarks: "",
    infusionTypeName: "",
    channelName: "",
    createByName: "",
    updateByName: "",
    orgName: ""
  }
  nextTick(() => {
    formRef.value.resetFields()
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  // proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.infusionTypeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构")
  }
  open.value = true;
  reset();
  // 设置默认的输液方式
  infusionTypeChange("1")
  title.value = "添加输液方式配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  reset();
  const _infusionTypeId = row.infusionTypeId || ids.value
  getInfusionType(_infusionTypeId).then((response: any) => {
    form.value = response.data;
    title.value = "修改输液方式配置";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      if (form.value.infusionTypeId != null) {
        updateInfusionType(form.value).then((response: any) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      } else {
        addInfusionType(form.value).then((response: any) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _infusionTypeIds = row.infusionTypeId ||
    ids.value;
  ElMessageBox.confirm('是否确认删除输液方式配置？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delInfusionType(_infusionTypeIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

/**
 * 途径方式值改变事件
 * @param e
 */
function administrationInfoChange(e: any) {
  const dict = toRaw(e)
  form.value.channel = dict.dictValue
}

/**
 * 输液方式值改变事件
 */
function infusionTypeChange(value: string) {
  form.value.infusionType = value;
  debugger
  const index = dictDataMap.value['infusion_type_dict'].findIndex(item => {
    return form.value.infusionType === item.dictValue
  })
  if (index > -1) {
    form.value.infusionTypeName = dictDataMap.value['infusion_type_dict'][index].dictLabel
  }
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/infusionType/export', {
    ...queryParams.value
  }, `infusionType_${new Date().getTime()}.xlsx`)
}

getList();
</script>
